﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;

namespace TaxiDispatchClient
{
    public partial class TaxiServerSetForm : DevExpress.XtraEditors.XtraForm
    {
        public TaxiServerSetForm()
        {
            InitializeComponent();
        }

        private void TaxiServerSetForm_Load(object sender, EventArgs e)
        {
            _isload = true;
            Thread thred = new Thread(BindData);
            thred.Start();
        }

        private bool _isload;
        private int _taxiId;
        private string _taxiNo;

        private void btn_select_Click(object sender, EventArgs e)
        {
           Thread  thread = new Thread(BindData);
           thread.Start();
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            if (btn_save.Tag.ToString() == "保存")
            {
                if (imageCombo_serverList.SelectedIndex == 0)
                {
                    XtraMessageBox.Show("请选择服务器！");
                    imageCombo_serverList.Focus();
                    return;
                }

                //修改当前选中的一辆出租车
                if (radioGroup_object.SelectedIndex == 0)
                {
                    if (XtraMessageBox.Show("是否修改车牌号为 " + label_taxiNo.Text + " 所用服务器",
                        "修改确认：", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                        return;
                    int serverid = int.Parse(imageCombo_serverList.Properties.Items[
                        imageCombo_serverList.SelectedIndex].Value.ToString());
                    if(MainForm.PositionService.UpdateServerIdByTaxiId(_taxiId,serverid))
                    {
                        XtraMessageBox.Show("修改成功！");                        
                    }
                    else
                    {
                        XtraMessageBox.Show("修改失败！");
                    }
                    gridControl1.Enabled = true;
                }
                //修改当前列表中所有出租车
                else
                {
                    if (XtraMessageBox.Show("是否修列表中所有出租车（共" + gridView1.DataRowCount +
                        "辆）所用服务器",
                           "修改确认：", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                        return;
                    progressBar1.Position = 0;
                    progressBar1.Visible = true;
                    btn_save.Enabled = false;
                    Thread  thread = new Thread(UpdateTaxisInGridView);
                    thread.Start();
                }
                btn_save.Tag = "修改";
                btn_save.Image = Properties.Resources.UserForm_btnmodify001;
                btn_cancel.Visible = false;
                imageCombo_serverList.Enabled = false;
                radioGroup_object.Enabled = false;
                
            }
            else
            {
                imageCombo_serverList.Enabled = true;
                radioGroup_object.Enabled = true;
                btn_save.Tag = "保存";
                btn_save.Image = Properties.Resources.UserForm_btnsave001;
                btn_cancel.Visible = true;
                gridControl1.Enabled = false;
            }
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            gridControl1.Enabled = true;
            btn_cancel.Visible = false;
            imageCombo_serverList.Enabled = false;
            imageCombo_serverList.Enabled = false;
            btn_save.Tag = "修改";
            btn_save.Image = Properties.Resources.UserForm_btnmodify001;            
            BindCurrentRow();
        }

        private void BindData()
        {
            DataSet ds = new DataSet();
            if (textEdit_paraValue.Text.Trim() == "")
            {
                ds = MainForm.PositionService.TaxiInfoGetList("");
            }
            else
            {
                string parameter = "";
                switch (radioGroup_SelectType.SelectedIndex)
                {
                    case 0:
                        parameter = "TaxiNo";
                        break;
                    case 1:
                        parameter = "TaxiType";
                        break;
                    case 2:
                        parameter = "Remark";
                        break;
                    case 3:
                        parameter = "Taxigroup";
                        break;
                }
                string parameterValue = textEdit_paraValue.Text;
                ds = MainForm.PositionService.TaxiInfoGetListWithPar(parameter, parameterValue);
            }
            if (ds != null)
            {
                BeginInvoke(new MethodInvoker(() =>
                {
                    gridControl1.DataSource = ds.Tables[0];
                    gridView1.GroupPanelText = "共计选择 " + ds.Tables[0].Rows.Count + " 辆出租车";
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        gridView1.FocusedRowHandle = 0;
                        gridView1_RowClick(null, null);
                        btn_save.Enabled = true;
                    }
                    else
                    {
                        btn_save.Enabled = false;
                    }
                }));
                if (_isload)
                {
                    BindServers();
                    SetGridStyle();
                    _isload = false;
                }
            }
            else
            {
                btn_save.Enabled = false;
            }

        }

        #region  绑定服务器列表 设置gridview格式
        private void BindServers()
        {

            ImageComboBoxItem itemNull = new ImageComboBoxItem("未设置",null);            
            BeginInvoke(new MethodInvoker(() =>
                        imageCombo_serverList.Properties.Items.Add(itemNull)));
            DataSet ds = MainForm.PositionService.ServerConfigGetList("");
            if(ds!=null && ds.Tables.Count>0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {                    
                    string id = row["id"].ToString();
                    string serverName = row["ServerName"].ToString();
                    ImageComboBoxItem item = new ImageComboBoxItem();                    
                    item.Description = serverName;
                    item.Value = id;
                    BeginInvoke(new MethodInvoker(() => 
                        imageCombo_serverList.Properties.Items.Add(item)));
                }
            }
            
        }
        
        private void SetGridStyle()
        {
            BeginInvoke(new MethodInvoker(() =>
            {
                gridView1.Columns["id"].Visible = false;
                gridView1.Columns["TaxiNo"].Caption = "牌照";
                gridView1.Columns["TaxiNo"].Width = 80;
                gridView1.Columns["TaxiGroupid"].Visible = false;
                gridView1.Columns["TaxiType"].Caption = "型号";
                gridView1.Columns["TaxiType"].Width = 90;
                gridView1.Columns["Taxigroup"].Caption = "分组";
                gridView1.Columns["Taxigroup"].Width = 90;
                gridView1.Columns["Remark"].Caption = "所属公司";             
            }));
        }
        #endregion

        private void BindCurrentRow()
        {
            DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            if (row == null) return;
            int id = int.Parse(row["id"].ToString());
            _taxiNo = row["TaxiNo"].ToString();
            _taxiId = id;
            Model.ServerConfigInfo model = MainForm.PositionService.GetServerConfigByTaxiId(id);
            if (model != null)
            {
                BeginInvoke(new MethodInvoker(() =>
                  {
                    imageCombo_serverList.SelectedIndex = 0;
                      if (radioGroup_object.SelectedIndex == 0)
                      {

                        label_taxiNo.Text = row["TaxiNo"].ToString();
                      }
                        if(model.id!=0)
                        {
                            foreach (ImageComboBoxItem item in imageCombo_serverList.Properties.Items)
                            {
                                if (item.Value == null) continue;
                                if (item.Value.ToString() == model.id.ToString())
                                {
                                    imageCombo_serverList.SelectedItem = item;
                                }
                            }
                        }                     
                   
                }));
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            Thread thread = new Thread(BindCurrentRow);
            thread.Start();
        }

        private void UpdateTaxisInGridView()
        {
            int count = gridView1.DataRowCount;
            BeginInvoke(new MethodInvoker(() =>
            {
                progressBar1.Properties.Maximum = count;
            }));
            int serverid = int.Parse(imageCombo_serverList.Properties.Items[
                       imageCombo_serverList.SelectedIndex].Value.ToString());            
            int falsed = 0;
            for (int i = 0; i < gridView1.DataRowCount; i++)
            {
                DataRow row = gridView1.GetDataRow(i);
                int id = int.Parse(row["id"].ToString());                
                if (!MainForm.PositionService.UpdateServerIdByTaxiId(id, serverid))
                    falsed++;
                BeginInvoke(new MethodInvoker(() =>
                {
                    progressBar1.Position++;
                }));
            }
            XtraMessageBox.Show("共计成功更新" + (count - falsed)
                + "条，失败" + falsed + "条记录");
            BeginInvoke(new MethodInvoker(() =>
            {
                progressBar1.Visible = false;
                btn_save.Enabled = true;
                radioGroup_object.SelectedIndex = 0;
                gridControl1.Enabled = true;
            }));

        }

        #region 窗体控件效果
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void PhoneUserForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
        #endregion

        private void radioGroup_object_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (radioGroup_object.SelectedIndex == 0)
            {
                if (!string.IsNullOrEmpty(_taxiNo))
                {
                    label_taxiNo.Text = _taxiNo;
                }
                else
                {
                    label_taxiNo.Text = "未选择";
                }
            }
            else
            {
                label_taxiNo.Text = "列表中的" + gridView1.DataRowCount + "出租车";
            }
        }

       
    }
}